import re
import datetime
from ac.models import LoginToken, MyUser
from django.http import JsonResponse, HttpResponseRedirect
from rest_framework import status
from django.conf import settings


def handle_xcsrftoken(string):
    """
    解析客户端传输的头文件参数
    :param string: TOKEN=AHWIEGOHOWAGAWIEGHOAWIHEGOAWI;PID=13545154651
    :return: {"TOKEN": "AHWIEGOHOWAGAWIEGHOAWIHEGOAWI", "PID": "13545154651"}
    """
    result = {}
    for i in string.split(";"):
        j = i.split("=")
        result[j[0]] = j[1]
    return result


class TokenMiddleware(object):
    """
    檢測token
    """
    # def process_request(self, request):
    #     url = request.META["PATH_INFO"].split("?")[0]
    #     # print(request.META['HTTP_USER_AGENT'])
    #     if '/api/workflow_approval/' in url and "HTTP_X_CSRFTOKEN" not in request.META:
    #         url = re.sub(r'(\d+)', r'', url)
    #     if url not in settings.NOT_AUTH_LIST:
    #         try:
    #             # token = re.findall(re.compile(r'.*?sessionid=(.*)'),request.META["HTTP_COOKIE"])[0].split(';')[0].replace(" ","")
    #             if not request.COOKIES:             # 前台调用
    #                 token = request.META["HTTP_X_CSRFTOKEN"]
    #                 token_obj = LoginToken.objects.filter(token=token, end_date__gt=datetime.datetime.now())
    #                 if token_obj:
    #                     import time
    #                     from ac.views import only_username_login
    #                     user_obj = MyUser.objects.filter(username__iexact=token_obj[0].user_id)[0]
    #                     only_username_login(request, user_obj)
    #                     token_obj[0].end_date = time.strftime("%Y-%m-%d %H:%M:%S",
    #                                                           time.localtime(int(time.time())
    #                                                                          + settings.SESSION_COOKIE_AGE))
    #                     token_obj[0].save()
    #                 else:
    #                     return JsonResponse({'data': "not auth"}, status=status.HTTP_203_NON_AUTHORITATIVE_INFORMATION)
    #             else:
    #                 if not request.user.username:           # API后台页面未登录
    #                     return HttpResponseRedirect("/ac/login?next=%s" % request.META["PATH_INFO"])
    #         except Exception as e:
    #             print(str(e), 222)
    #             return JsonResponse({'data': "not auth"}, status=status.HTTP_203_NON_AUTHORITATIVE_INFORMATION)
    #
    #
    # # def process_response(self, request, response):
    # #     if "sessionid" not in request.COOKIES.keys():
    # #         return response

    def process_request(self, request):
        url = request.META["PATH_INFO"].split("?")[0]
        # print(request.META['HTTP_USER_AGENT'])
        if '/api/workflow_approval/' in url and "HTTP_X_CSRFTOKEN" not in request.META:
            url = re.sub(r'(\d+)', r'', url)
        if url not in settings.NOT_AUTH_LIST:
            token = request.META.get("HTTP_X_CSRFTOKEN", None)

            if token:
                try:
                    token_obj = LoginToken.objects.filter(token=token, end_date__gt=datetime.datetime.now())
                    if token_obj:
                        import time
                        from ac.views import only_username_login
                        user_obj = MyUser.objects.filter(username__iexact=token_obj[0].user_id)[0]
                        only_username_login(request, user_obj)
                        token_obj[0].end_date = time.strftime("%Y-%m-%d %H:%M:%S",
                                                              time.localtime(int(time.time())
                                                                             + settings.SESSION_COOKIE_AGE))
                        token_obj[0].save()
                    else:
                        return JsonResponse({'data': "not auth"}, status=status.HTTP_203_NON_AUTHORITATIVE_INFORMATION)
                except Exception:
                    return JsonResponse({'data': "not auth"}, status=status.HTTP_203_NON_AUTHORITATIVE_INFORMATION)
            else:
                if not request.user.username:  # API后台页面未登录
                    return HttpResponseRedirect("/ac/login?next=%s" % request.META["PATH_INFO"])
